package midway.madness.post.podcast;

import java.io.IOException;

import midway.madness.R;
import midway.madness.utils.ApplicationEx;
import midway.madness.utils.SplashScreen;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class PodcastActivity extends Activity {

  private static final int maxSeekBar = 1000;
  private static final int secondsToSeek = 20;
  private SplashScreen splash;
  private MediaPlayer mediaPlayer = null;
  private boolean isPlaying = true;
  private Thread thread;
  private SeekBar seeker;
  private Handler handler;

  public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);

	splash = new SplashScreen(PodcastActivity.this);
	splash.showSplash();

	setContentView(R.layout.podcast_view);

	Intent intent = getIntent();

	// Ordering to make sure the seeker isn't null by the time we get down
	// to the listeners.
	// Shouldn't matter, since they aren't evaluated until the screen is set
	// and ready.
	seeker = (SeekBar) findViewById(R.id.podcast_seek_bar);
	
	handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what){
			case ApplicationEx.HANDLE_ERR:
				ApplicationEx appEx = (ApplicationEx) getApplication();
	    		AlertDialog alert = appEx.handleError(PodcastActivity.this, msg.getData().getString("errorMsg"));
	    		alert.setOnDismissListener(new OnDismissListener() {
					
					public void onDismiss(DialogInterface dialog) {
					  PodcastActivity.this.finish();
					}
				});
	    		splash.removeSplash();
	    		alert.show();
				break;
			default:
				super.handleMessage(msg);
				break;
			}
		}
		
	};
	
	new PodcastTask().execute(new String[] { intent.getStringExtra("url") });

	seeker.setMax(maxSeekBar);
	seeker.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

	  public void onStopTrackingTouch(SeekBar seekBar) {

	  }

	  public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub

	  }

	  public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
		if (fromUser) {
		  seekBar.setProgress(progress);
		  mediaPlayer.seekTo((mediaPlayer.getDuration() / maxSeekBar) * progress);
		}
	  }
	});
	((ImageButton) findViewById(R.id.podcast_play_btn)).setOnClickListener(new OnClickListener() {

	  public void onClick(View v) {
		ImageButton btn = (ImageButton) v;
		if (isPlaying) {
		  btn.setImageResource(R.drawable.play_img);
		  mediaPlayer.pause();
		} else {
		  btn.setImageResource(R.drawable.pause_img);
		  mediaPlayer.start();
		}
		isPlaying = !isPlaying;
	  }
	});
	((ImageButton) findViewById(R.id.podcast_skip_back)).setOnClickListener(new OnClickListener() {

	  public void onClick(View v) {
		int seekHere = mediaPlayer.getCurrentPosition() - ((secondsToSeek / 4) * 1000);
		mediaPlayer.seekTo(seekHere);
		seeker.setProgress((seekHere * maxSeekBar) / mediaPlayer.getDuration());
	  }
	});
	((ImageButton) findViewById(R.id.podcast_skip_forward))
			.setOnClickListener(new OnClickListener() {

			  public void onClick(View v) {
				int seekHere = mediaPlayer.getCurrentPosition() + (secondsToSeek * 1000);
				mediaPlayer.seekTo(seekHere);
				seeker.setProgress((seekHere * maxSeekBar) / mediaPlayer.getDuration());
			  }
			});
	((TextView) findViewById(R.id.podcast_title)).setText(intent.getStringExtra("title")
			+ "\n HOSTED BY: " + intent.getStringExtra("author").toUpperCase());
  }

  private class PodcastTask extends AsyncTask<String, Void, Void> {

	@Override
	protected Void doInBackground(String... params) {
	  String url = params[0];
	  mediaPlayer = new MediaPlayer();
	  mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

		public void onCompletion(MediaPlayer mp) {
		  PodcastActivity.this.finish();
		}
	  });
	  mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
	  try {
		mediaPlayer.setDataSource(url);
		mediaPlayer.prepare();
	  } catch (IllegalArgumentException e) {
		reportError();
	  } catch (IllegalStateException e) {
		reportError();
	  } catch (IOException e) {
		reportError();
	  }
	  return null;
	}

	protected void onPostExecute(Void v) {
	  splash.removeSplash();
	  mediaPlayer.start();
	  thread = new Thread(new Runnable() {

		public void run() {
		  while (null != mediaPlayer) {
			try {
			  // TODO: there may be some intermittent bug here...
			  seeker.setProgress((mediaPlayer.getCurrentPosition() * maxSeekBar)
					  / mediaPlayer.getDuration());
			  Thread.sleep(100);
			} catch (InterruptedException e) {
			  PodcastActivity.this.finish();
			} catch (IllegalStateException e2) {
			  // do nothing, we are already exiting.
			}
		  }
		}

	  });
	  thread.start();
	}
  }
  
  private void reportError(){
	Bundle data = new Bundle();
	data.putString("errorMsg", ((ApplicationEx) getApplication()).getMessage("unknown"));
	Message msg = new Message();
	msg.what = ApplicationEx.HANDLE_ERR;
	msg.setData(data);
	handler.sendMessage(msg);
  }

  public void finish() {
	super.finish();
	mediaPlayer.stop();
	mediaPlayer.release();
	mediaPlayer = null;
	if (null != thread) {
	  try {
		thread.join();
	  } catch (InterruptedException e) {
		// do nothing, we expect this.
	  }
	}
  }
}
